package com.modular.utils;

import cn.hutool.core.util.StrUtil;

public class DBUtils {
    /**
     * 转义mysql查询中参数,本函数不转义like语句
     *
     * @param paramName
     * @return
     */
    public static String escapeQuryParam(String paramName)
    {
        String result = null;
        if (!StrUtil.isEmpty(paramName))
        {
            paramName = paramName.trim();
            // mysql查询需要转义 % \ ' " _
            result = paramName.replaceAll("\\\\", "\\\\\\\\").replaceAll("%", "\\\\%").replaceAll("'", "\\\\\'").replaceAll("\"", "\\\\\"").replaceAll("_", "\\\\_");
        }
        return result;
    }

    public static String escapeQuryRightLikeParam(String paramName){
        if (StrUtil.isEmpty(paramName))
        {
            return null;
        }
        StringBuffer result = new StringBuffer();
        result.append(escapeQuryParam(paramName)).append("%");
        return result.toString();
    }

    /**
     * 转义like语句,并自动添加%%
     *
     * @param paramName
     * @return
     */
    public static String escapeQuryLikeParam(String paramName)
    {
        if (StrUtil.isEmpty(paramName))
        {
            return null;
        }
        StringBuilder result = new StringBuilder();
        result.append("%").append(escapeQuryParam(paramName)).append("%");
        return result.toString();
    }
}
